import requests
from django.shortcuts import render, redirect
from django.conf import settings
from www import models


def wx_login(request):
    wx_auth_app_id = settings.WX_AUTH_APP_ID
    wx_auth_url = settings.WX_AUTH_URL

    return render(request, 'wx_login.html', {"wx_auth_url": wx_auth_url, "wx_auth_app_id": wx_auth_app_id})


def wx_auth(request):
    # http://www.5xclass.cn/wx/auth/?code=011vr8Ga1u5lcI0DvoGa12O1Kz1vr8GD&state=undefined
    code = request.GET.get('code')

    if not code:
        return redirect("wx_login")

    app_id = settings.WX_AUTH_APP_ID
    app_secret = settings.WX_AUTH_APP_SECRET
    url = f"https://api.weixin.qq.com/sns/oauth2/access_token?appid={app_id}&secret={app_secret}&code={code}&grant_type=authorization_code"
    with requests.get(url) as res:
        res_dict = res.json()
    access_token = res_dict.get('access_token')
    openid = res_dict.get('openid')
    if not access_token or not openid:
        return redirect("wx_login")

    url = f"https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}"
    with requests.get(url) as res:
        res.encoding = 'utf-8'
        user_dict = res.json()
    name = user_dict.get("nickname")
    open_id = user_dict.get("openid")
    union_id = user_dict.get("unionid")
    avatar = user_dict.get("headimgurl")
    if not open_id or not union_id or not name or not avatar:
        return redirect("wx_login")

    # 数据库操作：新增用户 + 获取用户信息（union_id + open_id）
    instance, _ = models.User.objects.update_or_create(
        defaults={"name": name, "avatar": avatar},
        open_id=openid, union_id=union_id
    )

    request.session['user'] = {
        "id": instance.id, 'name': instance.name, "avatar": avatar, 'user_type': instance.user_type
    }

    return redirect("index")


def logout(request):
    request.session.clear()
    return redirect("wx_login")
